package mlog

import (
	"encoding/json"
	"log"
	"os"

	"github.com/dale-di/lumberjack"
)

//Logger 日志
type Logger struct {
	Log   *log.Logger
	Level int
}

const (
	//LogCritical 严重
	LogCritical = 1
	//LogWarning 警告
	LogWarning = 2
	//LogInfo 详细信息
	LogInfo = 4
	//LogDebug Debug级别
	LogDebug = 8
	//LogDebugv DebugV
	LogDebugv = 16
)

var lj *lumberjack.Logger

// New 创建新的Logger
func New(logFile string, level int) (*Logger, error) {
	logFlag := log.LstdFlags
	if level&LogDebug == LogDebug {
		logFlag = log.LstdFlags | log.Lshortfile
	}
	logger := Logger{
		Log:   log.New(os.Stdout, "", logFlag),
		Level: level,
	}
	switch logFile {
	case "stderr":
		logger.Log.SetOutput(os.Stderr)
	case "stdout":

	default:
		lj = &lumberjack.Logger{
			Filename:   logFile,
			MaxSize:    100, // megabytes
			MaxBackups: 10,
			// MaxAge:     28,   //days
			LocalTime: true,
			Compress:  false, // disabled by default
		}
		logger.Log.SetOutput(lj)
	}
	return &logger, nil
}

func (logger *Logger) Rotate() error {
	return lj.Rotate()
}

//LogInfo 日志处理
func (logger *Logger) LogInfo(format string, v ...interface{}) {
	if logger.Level&LogInfo == LogInfo {
		logger.Log.Printf("[Info] "+format, v...)
	}
}

//LogDebug 日志处理
func (logger *Logger) LogDebug(format string, v ...interface{}) {
	if logger.Level&LogDebug == LogDebug {
		// pc, _, line, _ := runtime.Caller(1)
		// f := runtime.FuncForPC(pc)
		// vv := []interface{}{f.Name(), line}
		// vv = append(vv, v...)
		// logger.Log.Printf("[Debug] (%s-%d) "+format, vv...)
		logger.Log.Printf("[Debug] "+format, v...)
	}
}

//LogDebug 日志处理
func (logger *Logger) LogDebugv(prefix string, v interface{}) {
	if logger.Level&LogDebugv == LogDebugv {
		tmp, _ := json.MarshalIndent(v, " ", "  ")
		logger.Log.Printf("[Debug] %s: %s", prefix, string(tmp))
	}
}

// LogDebug1 debug模式，将结构体记录到日志。
func (logger *Logger) LogDebug1(format string, v interface{}) {
	if logger.Level&LogDebug == LogDebug {
		tmp, _ := json.MarshalIndent(v, " ", "  ")
		logger.Log.Printf("[Debug1] %s: %s\n", format, string(tmp))
	}
}

//LogWarning 日志处理
func (logger *Logger) LogWarning(format string, v ...interface{}) {
	if logger.Level&LogWarning == LogWarning {
		// pc, _, line, _ := runtime.Caller(1)
		// f := runtime.FuncForPC(pc)
		// vv := []interface{}{f.Name(), line}
		// vv = append(vv, v...)
		// logger.Log.Printf("[Warin] (%s-%d) "+format, vv...)
		logger.Log.Printf("[Warin] "+format, v...)
	}
}

//LogCritical 日志处理
func (logger *Logger) LogCritical(format string, v ...interface{}) {
	if logger.Level&LogCritical == LogCritical {
		logger.Log.Printf("[Critical] "+format, v...)
	}
}

func (logger *Logger) Printf(format string, v ...interface{}) {
	logger.Log.Printf(format, v...)
}

func (logger *Logger) Fatalf(format string, v ...interface{}) {
	logger.Log.Printf(format, v...)
}
